#!/usr/bin/env bash
set -e

TARGET_FILE=$1

if [ -z "${TARGET_FILE}" ];then
  TARGET_FILE="/etc/nginx/conf.d/default.conf"
fi

echo "Start setup runtime context path"
echo "Runtime context path=${RUNTIME_CONTEXT_PATH}"

if [ -n "${RUNTIME_CONTEXT_PATH}" ];then
  safe_runtime_context_path=$(printf '%s' "${RUNTIME_CONTEXT_PATH}" | sed 's/\//\\\//g')
  case $(uname) in
    Darwin)
      sed -i .bak "s/location \/d\/health {/location ${safe_runtime_context_path}\/d\/health {/g" "${TARGET_FILE}"
      sed -i .bak "s/location \/ {/location ${safe_runtime_context_path} {/g" "${TARGET_FILE}"
      ;;
    Linux)
      sed -i "s/location \/d\/health {/location ${safe_runtime_context_path}\/d\/health {/g" "${TARGET_FILE}"
      sed -i "s/location \/ {/location ${safe_runtime_context_path} {/g" "${TARGET_FILE}"
      ;;
  esac
else
  case $(uname) in
    Darwin)
      sed -i .bak "s/alias \/app;/root \/app;/g" "${TARGET_FILE}"
      ;;
    Linux)
      sed -i "s/alias \/app;/root \/app;/g" "${TARGET_FILE}"
      ;;
  esac
fi



